<template>
  <div class="room-management">
    <!-- 上模块 -->
    <div class="top-section">
      <el-card shadow="hover">
        <div class="campus-header">
          <div class="left-panel">
            <el-avatar
                :size="160"
                shape="square"
                :data-campus="currentCampus?.park_id"
                class="campus-avatar"
            />
            <div class="campus-info">
              <div class="name-area">
                <h2 class="campus-name">{{ currentCampus?.park_name }}</h2>
                <el-select
                    v-model="selectedCampus"
                    placeholder="更换园区"
                    class="campus-switcher"
                    @change="updateCampusInfo"
                >
                  <el-option
                      v-for="campus in campuses"
                      :key="campus.park_id"
                      :label="campus.park_name || '未知园区'"
                      :value="campus.park_id"
                  />
                </el-select>
              </div>
              <div class="stats-grid">
                <div class="stat-item" v-for="(stat, index) in statsItems" :key="index">
                  <div class="stat-label">{{ stat.label }}</div>
                  <div class="stat-value">{{ stat.value }}</div>
                </div>
              </div>
            </div>
          </div>

          <el-button
              type="primary"
              icon="el-icon-office-building"
              @click="manageBuildings"
              class="manage-btn"
              size="medium"
          >
            管理楼宇
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 中模块 -->
    <div class="middle-section">
      <el-card shadow="hover" class="filter-card">
        <div class="filter-container">
          <div class="filter-row">
            <div class="filter-item">
              <span class="filter-label">厂房号：</span>
              <el-input
                  v-model="filters.roomNumber"
                  placeholder="输入厂房号搜索"
                  clearable
                  class="filter-input"
              />
            </div>

            <div class="filter-item">
              <span class="filter-label">状态：</span>
              <el-select
                  v-model="filters.status"
                  multiple
                  collapse-tags
                  placeholder="请选择状态"
                  class="filter-select"
              >
                <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </div>
          </div>

          <div class="filter-row">
            <div class="filter-item">
              <span class="filter-label">面积：</span>
              <el-select
                  v-model="filters.areaRange"
                  multiple
                  collapse-tags
                  placeholder="请选择面积范围"
                  class="filter-select"
              >
                <el-option
                    v-for="item in areaOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </div>

            <div class="filter-item">
              <span class="filter-label">楼宇：</span>
              <el-select
                  v-model="filters.building"
                  multiple
                  collapse-tags
                  placeholder="请选择楼宇"
                  class="filter-select"
              >
                <el-option
                    v-for="item in buildingOptions"
                    :key="item.value || ''"
                    :label="item.label || '未知数字'"
                    :value="item.value || ''"
                />
              </el-select>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 下模块 -->
    <div class="bottom-section">
      <el-card shadow="hover" class="table-card">
        <div class="table-header">
          <div class="header-left">
            <span class="summary-text">
              楼宇 {{ buildingCount }} | 厂房 {{ roomCount }}
            </span>
          </div>

          <div class="header-right">
            <el-button-group>
              <el-button type="primary" plain icon="el-icon-tickets" @click="manageFloors">管理楼层</el-button>
              <el-button type="primary" plain icon="el-icon-house" @click="manageRooms">管理厂房</el-button>
            </el-button-group>
          </div>
        </div>

        <el-table
            :data="filteredData"
            border
            style="width: 100%"
            class="data-table"
            v-loading="loading"
        >
          <el-table-column prop="building_name" label="楼宇" />
          <el-table-column prop="floor" label="楼层" />
          <el-table-column label="厂房号">
            <template #default="{ row }">
              <el-link type="primary" @click="viewRoomDetail(row)">{{ row.room_number }}</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型" />
          <el-table-column prop="area" label="租赁面积(㎡)" />
          <el-table-column prop="rent_price" label="租金" />
          <el-table-column prop="property_price" label="物业费" />
          <el-table-column prop="status" label="房源状态" />
        </el-table>
      </el-card>
    </div>

    <!-- 楼宇管理对话框 -->
    <el-dialog
        title="楼宇管理"
        v-model="buildingDialogVisible"
        width="80%"
        top="5vh"
        @close="handleBuildingDialogClose"
        class="building-manage-dialog"
    >
      <el-table :data="buildingList" border style="width: 100%">
        <el-table-column prop="name" label="楼宇名称" width="120" />
        <el-table-column prop="building_area" label="建筑面积(㎡)" width="120" />
        <el-table-column prop="rentable_space" label="可租面积(㎡)" width="120" />
        <el-table-column prop="room_number" label="厂房数量" width="100" />
        <el-table-column prop="building_address" label="楼宇地址" min-width="200" />
        <el-table-column label="操作" width="250" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <span class="action-text info" @click="viewBuildingDetail(row)">详情</span>
              <span class="action-text primary" @click="editBuilding(row)">编辑</span>
              <span class="action-text danger" @click="deleteBuilding(row.id)">删除</span>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <div class="footer-buttons">
          <el-button
              type="primary"
              icon="el-icon-plus"
              @click="addBuilding"
              class="add-building-btn"
          >
            添加楼宇
          </el-button>
          <el-button @click="buildingDialogVisible = false">关 闭</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 楼宇编辑对话框 -->
    <el-dialog
        :title="viewMode ? '楼宇详情' : editMode ? '编辑楼宇' : '添加楼宇'"
        v-model="editDialogVisible"
        width="700px"
        @close="resetBuildingForm"
    >
      <el-form
          :model="currentBuilding"
          :rules="buildingRules"
          ref="buildingFormRef"
          label-width="120px"
          :disabled="viewMode"
      >
        <el-form-item label="所属园区" prop="park_id">
          <el-select
              v-model="currentBuilding.park_id"
              placeholder="请选择所属园区"
              style="width: 100%"
          >
            <el-option
                v-for="campus in campuses"
                :key="campus.park_id"
                :label="campus.park_name"
                :value="campus.park_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="楼宇名称" prop="name">
          <el-input v-model="currentBuilding.name" placeholder="请输入楼宇名称" />
        </el-form-item>

        <el-form-item label="楼宇编号">
          <el-input v-model="currentBuilding.building_number" placeholder="请输入楼宇编号" />
        </el-form-item>

        <el-form-item label="地上楼层">
          <el-input-number
              v-model="currentBuilding.ground_floor_plan"
              :min="0"
              :max="100"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="地下楼层">
          <el-input-number
              v-model="currentBuilding.underground_floor_plan"
              :min="0"
              :max="10"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="楼宇地址" prop="building_address">
          <el-input
              v-model="currentBuilding.building_address"
              type="textarea"
              :rows="2"
              placeholder="请输入详细地址"
          />
        </el-form-item>

        <el-form-item label="产权性质" prop="property_region">
          <el-select
              v-model="currentBuilding.property_region"
              placeholder="请选择产权性质"
              style="width: 100%"
          >
            <el-option
                v-for="item in propertyTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="不动产编号">
          <el-input v-model="currentBuilding.real_estate_number" placeholder="请输入不动产编号" />
        </el-form-item>

        <el-form-item label="产权编号">
          <el-input v-model="currentBuilding.property_rights_number" placeholder="请输入产权编号" />
        </el-form-item>

        <el-form-item label="土地编号">
          <el-input v-model="currentBuilding.land_number" placeholder="请输入土地编号" />
        </el-form-item>

        <el-form-item label="建筑面积(㎡)" prop="building_area">
          <el-input-number
              v-model="currentBuilding.building_area"
              :min="100"
              :max="100000"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="产权面积(㎡)" prop="property_area">
          <el-input-number
              v-model="currentBuilding.property_area"
              :min="50"
              :max="currentBuilding.building_area"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="可租面积(㎡)">
          <el-input-number
              v-model="currentBuilding.rentable_space"
              :min="0"
              :max="currentBuilding.building_area"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="自用面积(㎡)">
          <el-input-number
              v-model="currentBuilding.self_used_area"
              :min="0"
              :max="currentBuilding.building_area"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="楼宇图片">
        <el-upload
            :action="uploadUrl"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            :file-list="fileList"
            :limit="1"
            accept=".jpg,.jpeg,.png"
        >
          <i class="el-icon-plus"></i>
          <template #tip>
            <div class="el-upload__tip">
              只能上传 jpg/png 文件，且不超过2MB
            </div>
          </template>
        </el-upload>
        <el-dialog v-model="dialogImageVisible" append-to-body class="picture-preview" >
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>

        <el-form-item label="楼宇设施服务">
          <el-checkbox-group v-model="currentBuilding.building_features">
            <el-checkbox value="中央空调">中央空调</el-checkbox>
            <el-checkbox value="电梯">电梯</el-checkbox>
            <el-checkbox value="监控覆盖">监控覆盖</el-checkbox>
            <el-checkbox value="食堂">食堂</el-checkbox>
            <el-checkbox value="会议室">会议室</el-checkbox>
            <el-checkbox value="智能门禁">智能门禁</el-checkbox>
            <el-checkbox value="人脸识别">人脸识别</el-checkbox>
            <el-checkbox value="高速宽带">高速宽带</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="楼宇简介" prop="building_introduction">
          <el-input
              v-model="currentBuilding.building_introduction"
              type="textarea"
              :rows="4"
              placeholder="请输入楼宇简介"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
            v-if="!viewMode"
            @click="editDialogVisible = false"
        >
          取 消
        </el-button>
        <el-button
            v-if="!viewMode"
            type="primary"
            @click="saveBuilding"
        >
          确 定
        </el-button>
        <el-button
            v-if="viewMode"
            type="primary"
            @click="editDialogVisible = false"
        >
          关 闭
        </el-button>
      </div>
    </el-dialog>

    <!-- 厂房详情对话框 -->
    <el-dialog
        title="厂房详情"
        v-model="roomDetailDialogVisible"
        width="50%"
        top="5vh"
        @close="currentRoom = null"
    >
      <el-descriptions
          v-if="currentRoom"
          :column="2"
          border
          size="medium"
      >
        <el-descriptions-item label="楼宇">{{ currentRoom.name }}</el-descriptions-item>
        <el-descriptions-item label="楼层">{{ currentRoom.floor }}</el-descriptions-item>
        <el-descriptions-item label="厂房号">{{ currentRoom.room_number }}</el-descriptions-item>
        <el-descriptions-item label="类型">{{ currentRoom.type }}</el-descriptions-item>
        <el-descriptions-item label="租赁面积">{{ currentRoom.area }}㎡</el-descriptions-item>
        <el-descriptions-item label="房源状态">{{ currentRoom.status }}</el-descriptions-item>
        <el-descriptions-item label="租金">{{ currentRoom.rent_price }}元/㎡·天</el-descriptions-item>
        <el-descriptions-item label="物业费">{{ currentRoom.property_price }}元/㎡·月</el-descriptions-item>
      </el-descriptions>
      <div v-else class="empty-tip">
        <el-empty description="未找到厂房信息" />
      </div>

      <template #footer>
        <el-button @click="roomDetailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleEditRoom">编辑厂房</el-button>
      </template>
    </el-dialog>

    <!-- 楼层管理对话框 -->
    <el-dialog
        title="楼层管理"
        v-model="floorDialogVisible"
        width="80%"
        top="5vh"
        @close="resetFloorForm"
    >
      <div class="dialog-header">
        <el-button
            type="primary"
            icon="el-icon-plus"
            @click="addFloor"
            class="add-floor-btn"
        >
          添加楼层
        </el-button>
      </div>
      <el-table :data="floorList" border style="width: 100%">
        <el-table-column prop="campus_name" label="所属园区" />
        <el-table-column prop="building_name" label="所属楼宇" />
        <el-table-column prop="floor_name" label="楼层名称" />
        <el-table-column prop="floor_code" label="楼层编号" />
        <el-table-column prop="floor_height" label="层高" />
        <el-table-column label="操作" width="250" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <span class="action-text primary" @click="editFloor(row)">编辑</span>
              <span class="action-text danger" @click="deleteFloor(row.id)">删除</span>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="floorDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 楼层编辑对话框 -->
    <el-dialog
        :title="floorEditMode ? '编辑楼层' : '添加楼层'"
        v-model="floorEditDialogVisible"
        width="700px"
        @close="resetFloorForm"
    >
      <el-form
          :model="currentFloor"
          :rules="floorRules"
          ref="floorFormRef"
          label-width="120px"
      >
        <el-form-item label="所属园区" prop="campus_id">
          <el-select
              v-model="currentFloor.campus_id"
              placeholder="请选择所属园区"
              style="width: 100%"
          >
            <el-option
                v-for="campus in campuses"
                :key="campus.park_id"
                :label="campus.park_name"
                :value="campus.park_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="所属楼宇" prop="building_id">
          <el-select
              v-model="currentFloor.building_id"
              placeholder="请选择所属楼宇"
              style="width: 100%"
          >
            <el-option
                v-for="building in currentCampusBuildings"
                :key="building.id"
                :label="building.name"
                :value="building.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="楼层名称" prop="floor_name">
          <el-input v-model="currentFloor.floor_name" placeholder="请输入楼层名称" />
        </el-form-item>

        <el-form-item label="楼层编号" prop="floor_code">
          <el-input v-model="currentFloor.floor_code" placeholder="请输入楼层编号" />
        </el-form-item>

        <el-form-item label="层高" prop="floor_height">
          <el-input-number
              v-model="currentFloor.floor_height"
              :min="0"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="floorEditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveFloor">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 厂房管理对话框 -->
    <el-dialog
        title="厂房管理"
        v-model="roomManagementDialogVisible"
        width="80%"
        top="5vh"
        @close="resetRoomManagementForm"
    >
      <div class="filter-row">
        <div class="filter-item">
          <span class="filter-label">楼：</span>
          <el-select
              v-model="roomFilters.building"
              placeholder="请选择楼"
              class="filter-select"
              @change="filterRooms"
          >
            <el-option
                v-for="building in currentCampusBuildings"
                :key="building.id"
                :label="building.name"
                :value="building.name"
            />
          </el-select>
        </div>
        <div class="filter-item">
          <span class="filter-label">楼层：</span>
          <el-select
              v-model="roomFilters.floor"
              placeholder="请选择楼层"
              class="filter-select"
              @change="filterRooms"
          >
            <el-option
                v-for="floor in getAvailableFloors(roomFilters.building)"
                :key="floor"
                :label="floor"
                :value="floor"
            />
          </el-select>
        </div>
        <el-button
            type="primary"
            icon="el-icon-plus"
            @click="addRoom"
            class="add-room-btn"
        >
          添加厂房
        </el-button>
      </div>

      <el-table
          :data="filteredRoomData"
          border
          style="width: 100%"
          class="data-table"
          v-loading="loadingRooms"
      >
        <el-table-column prop="room_number" label="厂房号" />
        <el-table-column prop="area" label="租赁面积(㎡)" />
        <el-table-column prop="status" label="状态" />
        <el-table-column prop="rent_price" label="租金" />
        <el-table-column prop="property_price" label="物业费" />
        <el-table-column label="操作" width="250" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <span class="action-text primary" @click="editRoom(row)">编辑</span>
              <span class="action-text danger" @click="deleteRoom(row)">删除</span>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="roomManagementDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 厂房编辑对话框 -->
    <el-dialog
        :title="roomEditMode ? '编辑厂房' : '添加厂房'"
        v-model="roomEditDialogVisible"
        width="700px"
        @close="resetRoomEditForm"
    >
      <el-form
          :model="currentRoomEdit"
          :rules="roomEditRules"
          ref="roomEditFormRef"
          label-width="120px"
      >
        <el-form-item label="所属园区" prop="park_id">
          <el-select
              v-model="currentRoomEdit.park_id"
              placeholder="请选择所属园区"
              style="width: 100%"
              disabled
          >
            <el-option
                v-for="campus in campuses"
                :key="campus.park_id"
                :label="campus.park_name"
                :value="campus.park_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="所属楼宇" prop="building_id">
          <el-select
              v-model="currentRoomEdit.building_id"
              placeholder="请选择所属楼宇"
              style="width: 100%"
              @change="updateAvailableFloors"
          >
            <el-option
                v-for="building in currentCampusBuildings"
                :key="building.id"
                :label="building.name"
                :value="building.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="楼层" prop="floor">
          <el-input v-model="currentRoomEdit.floor" placeholder="请输入楼层" />
        </el-form-item>

        <el-form-item label="厂房号" prop="room_number">
          <el-input v-model="currentRoomEdit.room_number" placeholder="请输入厂房号" />
        </el-form-item>

        <el-form-item label="类型">
          <el-input v-model="currentRoomEdit.type" placeholder="请输入厂房类型" />
        </el-form-item>

        <el-form-item label="租赁面积(㎡)" prop="area">
          <el-input-number
              v-model="currentRoomEdit.area"
              :min="1"
              :max="10000"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select
              v-model="currentRoomEdit.status"
              placeholder="请选择状态"
              style="width: 100%"
          >
            <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="租金(元/㎡·天)" prop="rent_price">
          <el-input-number
              v-model="currentRoomEdit.rent_price"
              :min="0"
              :precision="2"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="物业费(元/㎡·月)" prop="property_price">
          <el-input-number
              v-model="currentRoomEdit.property_price"
              :min="0"
              :precision="2"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="roomEditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoom">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script setup>
import {ref, reactive, computed, onMounted, watch, nextTick} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// API基础URL（从环境变量获取，自动适配环境）
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

// 响应式数据
const loading = ref(false)
const loadingRooms = ref(false)
const selectedCampus = ref(null)
const buildingDialogVisible = ref(false)
const roomDetailDialogVisible = ref(false)
const currentRoom = ref(null)
const editDialogVisible = ref(false)
const editMode = ref(false) // true为编辑模式，false为添加模式
const buildingFormRef = ref(null)
const dialogImageVisible = ref(false)
const dialogImageUrl = ref('')
const fileList = ref([])
const viewMode = ref(false) // 新增：查看模式标志
const roomEditDialogVisible = ref(false)
const roomEditMode = ref(false) // true为编辑模式，false为添加模式
const roomEditFormRef = ref(null)
const availableFloors = ref([]) // 当前楼宇下的可用楼层
const uploadUrl = ref(`${API_BASE_URL}/api/upload`) // 文件上传地址

const campuses = ref([])
const buildingList = ref([])
const floorList = ref([])
const roomData = ref([])
const tableData = ref([])
const buildingOptions = ref([])
const propertyTypes = ref([])

const filters = reactive({
  roomNumber: '',
  status: [],
  areaRange: [],
  building: []
})

const statusOptions = ref([
  { value: '已租', label: '已租' },
  { value: '待租', label: '待租' },
  { value: '自用', label: '自用' }
])

const areaOptions = ref([
  { value: '0-100', label: '100㎡以下' },
  { value: '100-200', label: '100-200㎡' },
  { value: '200-300', label: '200-300㎡' },
  { value: '300-500', label: '300-500㎡' },
  { value: '500-1000', label: '500-1000㎡' },
  { value: '1000+', label: '1000㎡以上' }
])

// 楼宇管理相关数据
const currentBuilding = reactive({
  id: null,
  park_id: selectedCampus.value, // 默认当前园区
  name: '',
  building_number: '',
  ground_floor_plan: 0,
  underground_floor_plan: 0,
  building_address: '',
  property_region: '',
  real_estate_number: '',
  property_rights_number: '',
  land_number: '',
  building_area: 1000,
  property_area: 800,
  rentable_space: 800,
  self_used_area: 0,
  building_images: '',
  building_features: [],
  building_introduction: '',
  room_number: 50
})

// 楼层管理相关数据
const floorDialogVisible = ref(false)
const floorEditDialogVisible = ref(false)
const floorEditMode = ref(false)
const floorFormRef = ref(null)
const roomManagementDialogVisible = ref(false)
const currentFloor = reactive({
  id: null,
  campus_id: selectedCampus.value,
  building_id: null,
  floor_name: '',
  floor_code: '',
  floor_height: 0
})

const floorRules = reactive({
  campus_id: [
    { required: true, message: '请选择所属园区', trigger: 'change' }
  ],
  building_id: [
    { required: true, message: '请选择所属楼宇', trigger: 'change' }
  ],
  floor_name: [
    { required: true, message: '请输入楼层名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  floor_code: [
    { required: true, message: '请输入楼层编号', trigger: 'blur' },
    { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
  ],
  floor_height: [
    { required: true, message: '请输入层高', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error('层高必须大于 0'))
        } else {
          callback()
        }
      }, trigger: 'blur' }
  ]
})

// 当前编辑的房间对象
const currentRoomEdit = reactive({
  id: null,
  park_id: selectedCampus.value,
  building_id: null,
  floor: '',
  room_number: '',
  type: '',
  area: 50,
  status: '待租',
  rent_price: 5.0,
  property_price: 2.0
})

// 房间编辑验证规则
const roomEditRules = reactive({
  building_id: [
    { required: true, message: '请选择所属楼宇', trigger: 'change' }
  ],
  floor: [
    { required: true, message: '请输入楼层', trigger: 'blur' }
  ],
  room_number: [
    { required: true, message: '请输入房间号', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  area: [
    { required: true, message: '请输入租赁面积', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error('面积必须大于 0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  rent_price: [
    { required: true, message: '请输入租金', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value < 0) {
          callback(new Error('租金不能为负数'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  property_price: [
    { required: true, message: '请输入物业费', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value < 0) {
          callback(new Error('物业费不能为负数'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 验证规则
const buildingRules = reactive({
  park_id: [
    { required: true, message: '请选择所属园区', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入楼宇名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  building_address: [
    { required: true, message: '请输入楼宇地址', trigger: 'blur' },
    { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  building_area: [
    { required: true, message: '请输入建筑面积', trigger: 'blur' }
  ],
  property_area: [
    { required: true, message: '请输入产权面积', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value > currentBuilding.building_area) {
          callback(new Error('产权面积不能大于建筑面积'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  building_introduction: [
    { required: true, message: '请输入楼宇简介', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ]
})

// 计算属性
const currentCampus = computed(() => {
  const campus = campuses.value.find(c =>
      c && (c.parkId === selectedCampus.value || c.park_id === selectedCampus.value)
  )
  return campus || {
    park_id: null,
    park_name: '未知园区',
    totalArea: 0,
    rentedArea: 0,
    availableArea: 0,
    usageRate: 0
  }
})

const statsItems = computed(() => {
  const campus = currentCampus.value
  if (!campus) return [
    { label: '总租赁面积', value: '0㎡' },
    { label: '已租面积', value: '0㎡' },
    { label: '使用率', value: '0%' },
    { label: '待租面积', value: '0㎡' }
  ]

  return [
    {
      label: '总租赁面积',
      value: `${campus.totalArea?.toLocaleString() || 0}㎡`
    },
    {
      label: '已租面积',
      value: `${campus.rentedArea?.toLocaleString() || 0}㎡`
    },
    {
      label: '使用率',
      value: `${campus.usageRate || 0}%`
    },
    {
      label: '待租面积',
      value: `${campus.availableArea?.toLocaleString() || 0}㎡`
    }
  ]
})

const filteredData = computed(() => {
  return tableData.value.filter(item => {
    // 原有的筛选条件
    const roomNumberMatch = !filters.roomNumber || item.room_number.includes(filters.roomNumber)
    const statusMatch = !filters.status.length || filters.status.includes(item.status)
    const buildingMatch = !filters.building.length || filters.building.includes(item.name)

    // 新增面积范围筛选
    const areaMatch = !filters.areaRange.length || filters.areaRange.some(range => {
      const area = item.area || 0
      switch (range) {
        case '0-100':
          return area < 100
        case '100-200':
          return area >= 100 && area < 200
        case '200-300':
          return area >= 200 && area < 300
        case '300-500':
          return area >= 300 && area < 500
        case '500-1000':
          return area >= 500 && area < 1000
        case '1000+':
          return area >= 1000
        default:
          return true
      }
    })

    return roomNumberMatch && statusMatch && buildingMatch && areaMatch
  })
})

const buildingCount = computed(() => {
  return new Set(tableData.value.map(item => item.name)).size
})

const roomCount = computed(() => {
  return tableData.value.length
})

const roomFilters = reactive({
  building: '',
  floor: ''
})

const currentCampusBuildings = computed(() => {
  return buildingList.value.filter(b =>
      b && (b.parkId === selectedCampus.value || b.park_id === selectedCampus.value)
  )
})

const filteredRoomData = computed(() => {
  return roomData.value.filter(item =>
      (!roomFilters.building || item.building_name === roomFilters.building) &&
      (!roomFilters.floor || item.floor === roomFilters.floor)
  )
})

// API调用方法
const fetchParks = async () => {
  try {
    loading.value = true
    const response = await axios.get(`${API_BASE_URL}/api/parks`)
    console.log('获取园区数据:', response.data)

    // 处理驼峰转下划线
    campuses.value = (response.data || []).map(campus => ({
      park_id: campus.parkId,
      park_name: campus.parkName,
      address: campus.address,
      description: campus.description,
      totalArea: campus.totalArea,
      rentedArea: campus.rentedArea,
      availableArea: campus.availableArea,
      usageRate: campus.usageRate,
      createTime: campus.createTime,
      updateTime: campus.updateTime
    }))

    console.log('转换后的园区数据:', campuses.value)

    if (campuses.value.length > 0 && !selectedCampus.value) {
      selectedCampus.value = campuses.value[0].park_id
      console.log('设置默认园区ID:', selectedCampus.value)
    }
  } catch (error) {
    console.error('获取园区列表失败:', error)
    ElMessage.error('获取园区列表失败')
  } finally {
    loading.value = false
  }
}

const fetchBuildings = async () => {
  if (!selectedCampus.value) {
    ElMessage.warning('请先选择园区')
    return
  }

  try {
    loading.value = true
    const response = await axios.get(`${API_BASE_URL}/api/parks/${selectedCampus.value}/buildings`)
    console.log('原始楼宇数据:', response.data)

    // 处理楼宇数据的字段映射
    buildingList.value = (response.data || []).map(building => ({
      id: building.id,
      park_id: building.parkId,
      name: building.name,
      building_number: building.building_number,
      ground_floor_plan: building.groundFloorPlan,
      underground_floor_plan: building.undergroundFloorPlan,
      building_address: building.buildingAddress,
      property_region: building.propertyRegion,
      real_estate_number: building.realEstateNumber,
      property_rights_number: building.propertyRightsNumber,
      land_number: building.landNumber,
      building_area: building.buildingArea,
      property_area: building.propertyArea,
      rentable_space: building.rentableSpace,
      self_used_area: building.selfUsedArea,
      building_images: building.buildingImages,
      building_features: building.buildingFeatures || '',
      building_introduction: building.buildingIntroduction,
      room_number: building.roomNumber
    })).filter(building =>
        building && building.id != null && building.name != null
    )

    console.log('转换后的楼宇数据:', buildingList.value)
    console.log('产权性质字段示例:', buildingList.value.map(b => ({id: b.id, property_region: b.property_region})))
  } catch (error) {
    console.error('获取楼宇列表失败:', error)
    ElMessage.error('获取楼宇列表失败')
  } finally {
    loading.value = false
  }
}

const fetchFloors = async () => {
  try {
    const params = {}

    // 添加园区ID过滤
    if (selectedCampus.value) {
      params.campusId = selectedCampus.value
    }

    const response = await axios.get(`${API_BASE_URL}/api/parks/floors`, { params })
    console.log('原始楼层数据:', response.data)

    // 处理楼层数据的字段映射
    floorList.value = (response.data || []).map(floor => {
      const floorObj = {
        id: floor.id,
        campus_id: floor.campusId,
        building_id: floor.buildingId,
        floor_name: floor.floorName,
        floor_code: floor.floorCode,
        floor_height: floor.floorHeight,
        createTime: floor.createTime,
        updateTime: floor.updateTime
      }

      // 查找对应的园区信息
      const campus = campuses.value.find(c =>
          c.park_id === floor.campusId || c.parkId === floor.campusId
      )
      if (campus) {
        floorObj.campus_name = campus.park_name || '未知园区'
      } else {
        floorObj.campus_name = '未知园区'
      }

      // 查找对应的楼宇信息
      const building = buildingList.value.find(b => b.id === floor.buildingId)
      if (building) {
        floorObj.building_name = building.name || '未知楼宇'
      } else {
        floorObj.building_name = '未知楼宇'
      }

      return floorObj
    })

    console.log('转换后的楼层数据:', floorList.value)
  } catch (error) {
    console.error('获取楼层列表失败:', error)
    ElMessage.error('获取楼层列表失败')
  }
}

const fetchRooms = async () => {
  if (!selectedCampus.value) {
    ElMessage.warning('请先选择园区')
    return
  }
  try {
    loading.value = true
    const response = await axios.get(`${API_BASE_URL}/api/parks/rooms`, {
      params: {
        parkId: selectedCampus.value
      }
    })
    console.log('原始厂房数据:', response.data)

    // 处理房间数据的字段映射
    const rooms = (response.data || []).map(room => {
      const roomObj = {
        id: room.id,
        park_id: room.parkId,
        building_id: room.buildingId,
        room_number: room.roomNumber,
        floor: room.floor,
        type: room.type,
        area: room.area,
        status: room.status,
        rent_price: room.rentPrice,
        property_price: room.propertyPrice,
        remark: room.remark,
        createTime: room.createTime,
        updateTime: room.updateTime
      }

      // 查找对应的楼宇信息
      const building = buildingList.value.find(b => b.id === room.buildingId)
      if (building) {
        roomObj.name = building.name
        roomObj.building_name = building.name
      } else {
        roomObj.name = '未知楼宇'
        roomObj.building_name = '未知楼宇'
      }

      return roomObj
    }).filter(room =>
        room && room.id != null && room.room_number != null
    )

    roomData.value = rooms
    tableData.value = rooms
    console.log('转换后的厂房数据:', roomData.value)
  } catch (error) {
    console.error('获取厂房列表失败:', error)
    ElMessage.error('获取厂房列表失败')
  } finally {
    loading.value = false
  }
}

// 获取产权性质
const fetchPropertyTypes = async () => {
  try {
    console.log('开始获取产权性质数据...')
    const response = await axios.get(`${API_BASE_URL}/api/property-types`)
    console.log('获取产权性质数据成功:', response.data)

    propertyTypes.value = response.data.map(item => ({
      value: item.value,
      label: item.label
    }))

    console.log('转换后的产权性质选项:', propertyTypes.value)
  } catch (error) {
    console.error('获取产权性质列表失败:', error)
    // 降级方案：使用默认值
    propertyTypes.value = [
      { value: 'STATE_OWNED', label: '国有' },
      { value: 'COLLECTIVE', label: '集体' },
      { value: 'PRIVATE', label: '私有' },
      { value: 'FOREIGN', label: '外资' },
      { value: 'JOINT_VENTURE', label: '合资' }
    ]
    ElMessage.warning('使用默认产权性质选项')
  }
}

// 方法
const viewRoomDetail = (row) => {
  currentRoom.value = { ...row }
  roomDetailDialogVisible.value = true
}

const handleEditRoom = () => {
  roomDetailDialogVisible.value = false
  editRoom(currentRoom.value)
}

const manageBuildings = async () => {
  await fetchBuildings()
  buildingDialogVisible.value = true
}

const addBuilding = () => {
  editMode.value = false
  viewMode.value = false
  resetBuildingForm()
  editDialogVisible.value = true
}


const editBuilding = (building) => {
  console.log('编辑楼宇数据:', building)
  console.log('产权性质值:', building.property_region)
  console.log('设施服务原始数据:', building.building_features)

  editMode.value = true
  viewMode.value = false

  // 重置表单
  resetBuildingForm()

  // 复制楼宇数据到表单
  Object.keys(currentBuilding).forEach(key => {
    if (building.hasOwnProperty(key)) {
      currentBuilding[key] = building[key]
    }
  })

  // 特别确保 property_region 正确设置
  if (building.property_region) {
    currentBuilding.property_region = building.property_region
  } else if (building.propertyRegion) {
    // 如果后端返回的是 propertyRegion 字段
    currentBuilding.property_region = building.propertyRegion
  }

  // 确保ID正确设置
  currentBuilding.id = building.id

  // 处理设施服务字段
  if (building.building_features) {
    if (typeof building.building_features === 'string') {
      // 如果是字符串，按逗号分割成数组
      currentBuilding.building_features = building.building_features.split(',').filter(item => item.trim() !== '')
    } else if (Array.isArray(building.building_features)) {
      // 如果已经是数组，直接使用
      currentBuilding.building_features = building.building_features
    } else {
      currentBuilding.building_features = []
    }
  } else {
    currentBuilding.building_features = []
  }

  console.log('设置后的设施服务数据:', currentBuilding.building_features)

  // 处理图片显示
  if (building.building_images) {
    fileList.value = [{
      name: '楼宇图片',
      url: building.building_images
    }]
    currentBuilding.building_images = building.building_images
  } else {
    fileList.value = []
    currentBuilding.building_images = ''
  }

  console.log('设置后的表单数据:', currentBuilding)
  console.log('产权性质字段值:', currentBuilding.property_region)
  console.log('可用产权性质选项:', propertyTypes.value)

  editDialogVisible.value = true
}

const handleRemove = (file, fileList) => {
  console.log('删除文件:', file)
  currentBuilding.building_images = ''
  fileList.value = []
  ElMessage.success('图片已删除')
}

const viewBuildingDetail = (building) => {
  viewMode.value = true
  Object.assign(currentBuilding, building)

  if (building.building_features) {
    if (typeof building.building_features === 'string') {
      currentBuilding.building_features = building.building_features.split(',').filter(item => item.trim() !== '')
    } else if (!Array.isArray(building.building_features)) {
      currentBuilding.building_features = []
    }
  } else {
    currentBuilding.building_features = []
  }

  if (building.building_images) {
    fileList.value = [{
      name: '楼宇图片',
      url: building.building_images
    }]
  }

  editDialogVisible.value = true
}

const deleteBuilding = async (id) => {
  try {
    await ElMessageBox.confirm('确定删除该楼宇吗？删除后无法恢复', '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
      customClass: 'delete-confirm-box'
    })

    await axios.delete(`${API_BASE_URL}/api/parks/buildings/${id}`)
    ElMessage.success('楼宇删除成功')
    await fetchBuildings()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除楼宇失败:', error)
      ElMessage.error('删除楼宇失败')
    }
  }
}

const saveBuilding = async () => {
  try {
    await buildingFormRef.value.validate()


    let buildingFeatures = ''
    if (Array.isArray(currentBuilding.building_features)) {
      buildingFeatures = currentBuilding.building_features.filter(item => item && item.trim() !== '').join(',')
    } else if (typeof currentBuilding.building_features === 'string') {
      buildingFeatures = currentBuilding.building_features
    }

    // 准备提交的数据
    const submitData = {
      id: currentBuilding.id,
      parkId: currentBuilding.park_id,
      name: currentBuilding.name,
      buildingNumber: currentBuilding.building_number,
      groundFloorPlan: currentBuilding.ground_floor_plan,
      undergroundFloorPlan: currentBuilding.underground_floor_plan,
      buildingAddress: currentBuilding.building_address,
      propertyRegion: currentBuilding.property_region || '',
      realEstateNumber: currentBuilding.real_estate_number,
      propertyRightsNumber: currentBuilding.property_rights_number,
      landNumber: currentBuilding.land_number,
      buildingArea: Number(currentBuilding.building_area) || 0,
      propertyArea: Number(currentBuilding.property_area) || 0,
      rentableSpace: Number(currentBuilding.rentable_space) || 0,
      selfUsedArea: Number(currentBuilding.self_used_area) || 0,
      buildingImages: currentBuilding.building_images || '',
      buildingFeatures: buildingFeatures,
      buildingIntroduction: currentBuilding.building_introduction || '',
      roomNumber: Number(currentBuilding.room_number) || 0
    }

    console.log('准备提交的数据:', submitData)
    console.log('编辑模式:', editMode.value)

    // 确保没有undefined值
    Object.keys(submitData).forEach(key => {
      if (submitData[key] === undefined) {
        submitData[key] = null
      }
    })

    let response
    if (editMode.value) {
      // 更新楼宇
      response = await axios.put(`${API_BASE_URL}/api/parks/buildings/${currentBuilding.id}`, submitData)
      ElMessage.success('楼宇信息更新成功')
    } else {
      // 添加新楼宇 - 移除id字段
      delete submitData.id
      response = await axios.post(`${API_BASE_URL}/api/parks/buildings`, submitData)
      ElMessage.success('楼宇添加成功')
    }

    console.log('保存成功响应:', response.data)

    editDialogVisible.value = false
    await fetchBuildings()
    updateBuildingOptions()
  } catch (error) {
    console.error('保存楼宇失败:', error)
    if (error.response) {
      console.error('后端错误响应:', error.response.data)
      ElMessage.error(`保存失败: ${error.response.data.message || error.response.data}`)
    } else if (error.request) {
      console.error('请求未发送:', error.request)
      ElMessage.error('网络错误，请检查连接')
    } else {
      ElMessage.error('保存楼宇失败')
    }
  }
}


const resetBuildingForm = () => {
  viewMode.value = false
  Object.assign(currentBuilding, {
    id: null,
    park_id: selectedCampus.value,
    name: '',
    building_number: '',
    ground_floor_plan: 0,
    underground_floor_plan: 0,
    building_address: '',
    property_region: '',
    real_estate_number: '',
    property_rights_number: '',
    land_number: '',
    building_area: 1000,
    property_area: 800,
    rentable_space: 800,
    self_used_area: 0,
    building_images: '',
    building_features: [],
    building_introduction: '',
    room_number: 50
  })
  fileList.value = []
}

const updateBuildingOptions = () => {
  buildingOptions.value = currentCampusBuildings.value.map(b => ({
    value: b.name,
    label: b.name
  }))
}

const handleBuildingDialogClose = () => {
  updateBuildingOptions()
}

const updateCampusInfo = () => {
  fetchBuildings()
  fetchRooms()
  updateBuildingOptions()
}

const manageFloors = async () => {
  try {
    loading.value = true

    // 确保园区数据已加载
    if (campuses.value.length === 0) {
      await fetchParks()
    }

    // 确保楼宇数据已加载
    if (buildingList.value.length === 0 && selectedCampus.value) {
      await fetchBuildings()
    }

    // 重新加载楼层数据（会使用当前园区ID过滤）
    await fetchFloors()

    floorDialogVisible.value = true
  } catch (error) {
    console.error('打开楼层管理失败:', error)
    ElMessage.error('打开楼层管理失败')
  } finally {
    loading.value = false
  }
}

const addFloor = () => {
  floorEditMode.value = false
  resetFloorForm()
  floorEditDialogVisible.value = true
}

const editFloor = (floor) => {
  floorEditMode.value = true
  // 正确映射字段
  Object.assign(currentFloor, {
    id: floor.id,
    campus_id: floor.campus_id,
    building_id: floor.building_id,
    floor_name: floor.floor_name,
    floor_code: floor.floor_code,
    floor_height: floor.floor_height
  })
  floorEditDialogVisible.value = true
}

const deleteFloor = async (id) => {
  try {
    await ElMessageBox.confirm('确定删除该楼层吗？删除后无法恢复', '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
      customClass: 'delete-confirm-box'
    })

    await axios.delete(`${API_BASE_URL}/api/parks/floors/${id}`)
    ElMessage.success('楼层删除成功')
    await fetchFloors()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除楼层失败:', error)
      ElMessage.error('删除楼层失败')
    }
  }
}

const saveFloor = async () => {
  try {
    await floorFormRef.value.validate()

    // 构建符合后端格式的数据
    const floorData = {
      id: currentFloor.id,
      campusId: currentFloor.campus_id,
      buildingId: currentFloor.building_id,
      floorName: currentFloor.floor_name,
      floorCode: currentFloor.floor_code,
      floorHeight: currentFloor.floor_height
    }

    if (floorEditMode.value) {
      // 更新楼层
      await axios.put(`${API_BASE_URL}/api/parks/floors/${currentFloor.id}`, floorData)
      ElMessage.success('楼层信息更新成功')
    } else {
      // 添加新楼层
      await axios.post(`${API_BASE_URL}/api/parks/floors`, floorData)
      ElMessage.success('楼层添加成功')
    }

    floorEditDialogVisible.value = false
    await fetchFloors()
  } catch (error) {
    console.error('保存楼层失败:', error)
    if (error.response) {
      console.error('后端错误响应:', error.response.data)
      ElMessage.error(`保存失败: ${error.response.data.message || error.response.data}`)
    } else {
      ElMessage.error('保存楼层失败')
    }
  }
}

// 更新可用楼层列表
const updateAvailableFloors = (buildingId) => {
  if (!buildingId) {
    availableFloors.value = []
    return
  }
  // 过滤出当前楼宇的楼层
  availableFloors.value = floorList.value.filter(floor => floor.building_id === buildingId)
}

// 添加房间
const addRoom = () => {
  roomEditMode.value = false
  resetRoomEditForm()
  roomEditDialogVisible.value = true
}

// 编辑厂房
const editRoom = (room) => {
  roomEditMode.value = true
  // 查找厂房的完整信息
  const fullRoom = roomData.value.find(r => r.id === room.id)
  if (fullRoom) {
    Object.assign(currentRoomEdit, {
      id: fullRoom.id,
      park_id: fullRoom.park_id,
      building_id: fullRoom.building_id,
      floor: fullRoom.floor,
      room_number: fullRoom.room_number,
      type: fullRoom.type,
      area: fullRoom.area,
      status: fullRoom.status,
      rent_price: fullRoom.rent_price,
      property_price: fullRoom.property_price
    })
    roomEditDialogVisible.value = true
  }else{
    ElMessage.error('未找到房间信息')
  }
}

// 保存厂房
const saveRoom = async () => {
  try {
    await roomEditFormRef.value.validate()

    const roomData = {
      id: currentRoomEdit.id,
      parkId: currentRoomEdit.park_id,
      buildingId: currentRoomEdit.building_id,
      roomNumber: currentRoomEdit.room_number,
      floor: currentRoomEdit.floor,
      type: currentRoomEdit.type || null,
      area: Number(currentRoomEdit.area) || 0,
      status: currentRoomEdit.status,
      rentPrice: Number(currentRoomEdit.rent_price) || 0,
      propertyPrice: Number(currentRoomEdit.property_price) || 0,
      remark: ''
    }
    console.log('提交的厂房数据:', roomData)
    // 遍历所有属性，将undefined转换为null
    Object.keys(roomData).forEach(key => {
      if (roomData[key] === undefined) {
        roomData[key] = null
      }
    })

    if (roomEditMode.value) {
      // 更新房间
      await axios.put(`${API_BASE_URL}/api/parks/rooms/${currentRoomEdit.id}`, roomData)
      ElMessage.success('厂房更新成功')
    } else {
      delete roomData.id
      // 添加新房间
      await axios.post(`${API_BASE_URL}/api/parks/rooms`, roomData)
      ElMessage.success('厂房添加成功')
    }

    roomEditDialogVisible.value = false
    await fetchRooms()
  } catch (error) {
    console.error('保存厂房失败:', error)
    if (error.response) {
      console.error('后端错误响应:', error.response.data)
      ElMessage.error(`保存失败: ${error.response.data.message || error.response.data}`)
    } else if (error.request) {
      console.error('请求未发送:', error.request)
      ElMessage.error('网络错误，请检查连接')
    } else {
      ElMessage.error('保存厂房失败')
    }
  }
}

// 重置房间编辑表单
const resetRoomEditForm = () => {
  roomEditMode.value = false
  Object.assign(currentRoomEdit, {
    id: null,
    park_id: selectedCampus.value,
    building_id: null,
    floor: '',
    room_number: '',
    type: '办公室',
    area: 50,
    status: '待租',
    rent_price: 5.0,
    property_price: 2.0
  })
}

const resetFloorForm = () => {
  floorEditMode.value = false
  Object.assign(currentFloor, {
    id: null,
    campus_id: selectedCampus.value,
    building_id: null,
    floor_name: '',
    floor_code: '',
    floor_height: 3.0
  })
}

const getAvailableFloors = (building) => {
  if (!building) return []
  const floors = [...new Set(roomData.value
      .filter(item => item.building_name === building)
      .map(item => item.floor)
  )]
  return floors.sort()
}

const manageRooms = async () => {
  // 重置筛选条件
  roomFilters.building = ''
  roomFilters.floor = ''

  loadingRooms.value = true
  try {
    await fetchRooms()
    roomManagementDialogVisible.value = true
  } finally {
    loadingRooms.value = false
  }
}

const filterRooms = () => {
  if (roomFilters.building && !getAvailableFloors(roomFilters.building).includes(roomFilters.floor)) {
    roomFilters.floor = ''
  }
}

const deleteRoom = async (room) => {
  try {
    await ElMessageBox.confirm('确定删除该厂房吗？删除后无法恢复', '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
      customClass: 'delete-confirm-box'
    })

    await axios.delete(`${API_BASE_URL}/api/parks/rooms/${room.id}`)
    ElMessage.success('厂房删除成功')
    await fetchRooms()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除厂房失败:', error)
      ElMessage.error('删除厂房失败')
    }
  }
}

const resetRoomManagementForm = () => {
  roomFilters.building = ''
  roomFilters.floor = ''
}


const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogImageVisible.value = true

  // 使用 nextTick 确保 DOM 更新后设置层级
  nextTick(() => {
    const previewDialog = document.querySelector('.picture-preview');
    if (previewDialog) {
      previewDialog.style.zIndex = '10002';
      const overlay = previewDialog.previousElementSibling;
      if (overlay && overlay.classList.contains('el-overlay')) {
        overlay.style.zIndex = '10001';
      }
    }
  })
}

const handleUploadSuccess = (response, file) => {
  console.log('上传响应:', response)
  console.log('文件信息:', file)

  // 根据实际返回数据结构调整
  if (response && response.code === 200) {
    // 如果返回结构是 {code: 200, data: {url: '...'}}
    currentBuilding.building_images = response.data.url
    ElMessage.success('图片上传成功')
  } else if (response && response.url) {
    // 如果直接返回URL
    currentBuilding.building_images = response.url
    ElMessage.success('图片上传成功')
  } else if (response && typeof response === 'string') {
    // 如果返回的就是URL字符串
    currentBuilding.building_images = response
    ElMessage.success('图片上传成功')
  } else {
    console.error('未知的响应格式:', response)
    ElMessage.error('图片上传失败：未知的响应格式')
  }
}

// 上传前的验证
const beforeUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('只能上传 JPG/PNG 格式的图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 上传错误处理
const handleUploadError = (error, file, fileList) => {
  console.error('上传错误:', error)
  ElMessage.error('图片上传失败')
}

onMounted(async () => {
  await fetchParks()
  await fetchPropertyTypes()
  if (campuses.value.length > 0 && !selectedCampus.value) {
    selectedCampus.value = campuses.value[0].park_id
    // 确保先加载楼宇数据，再加载房间数据
    await fetchBuildings()
    await fetchRooms()
  }
  await fetchFloors()
})

// 监听园区选择的变化
watch(selectedCampus, async () => {
  if (selectedCampus.value) {
    await fetchBuildings() // 先加载楼宇数据
    await fetchRooms()     // 再加载房间数据
    updateBuildingOptions()
    resetRoomManagementForm()
  }
})
</script>

<style scoped>
/* 样式保持不变 */
.campus-avatar[data-campus="1"] {
  background-image: url('https://img95.699pic.com/photo/60022/4177.jpg_wh860.jpg');
  background-size: cover;
  background-position: center;
}

.campus-avatar[data-campus="2"] {
  background-image: url('https://img95.699pic.com/photo/50082/8358.jpg_wh860.jpg');
  background-size: cover;
  background-position: center;
}

/* 其他样式保持不变 */
.empty-tip {
  padding: 40px 0;
  text-align: center;
}

:deep(.el-descriptions) {
  margin: 10px 0;
}

:deep(.el-descriptions__label) {
  width: 120px;
  font-weight: bold;
  background-color: #f5f7fa;
}

:deep(.el-descriptions__content) {
  padding-left: 20px;
}
.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}
.footer-buttons {
  display: flex;
  justify-content: flex-end; /* 靠右对齐 */
  gap: 10px; /* 按钮间距 */
}

.el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
}
.el-checkbox {
  width: 120px;
  margin-right: 10px;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}
.room-management {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  background: #f5f7fa;
}

/* 上模块样式 */
.top-section .el-card {
  border-radius: 8px;
}

.campus-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  min-height: 200px;
  position: relative;
}

.left-panel {
  display: flex;
  gap: 30px;
  width: 75%;
}

.campus-avatar {
  flex-shrink: 0;
  box-shadow: 0 4px 16px rgba(0,0,0,0.1);
  height: 160px;
  width: 160px;
}

.campus-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.name-area {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 25px;
}

.campus-name {
  margin: 0;
  font-size: 24px;
  color: #303133;
  font-weight: 600;
}

.campus-switcher {
  width: 180px;
}

.campus-switcher :deep() .el-input__inner {
  height: 36px;
  line-height: 36px;
  font-size: 14px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.stat-item {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  border-left: 4px solid var(--el-color-primary);
}

.stat-label {
  color: #909399;
  font-size: 14px;
  margin-bottom: 6px;
}

.room-edit-form .el-form-item {
  margin-bottom: 20px;
}

.room-edit-form .el-input-number {
  width: 100%;
}

.stat-value {
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.manage-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  padding: 10px 20px;
  font-size: 14px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  transition: all 0.3s ease;
}

.manage-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

/* 中模块样式 */
.filter-card .el-card__body {
  padding: 20px;
}

.filter-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.filter-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-label {
  min-width: 60px;
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.filter-input,
.filter-select {
  flex: 1;
  max-width: 400px;
}

/* 下模块样式 */
.table-card .el-card__body {
  padding: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.summary-text {
  color: #606266;
  font-size: 14px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.data-table {
  margin-top: 16px;
}

.picture-preview {
  z-index: 10002 !important;
}

:deep(.picture-preview) {
  z-index: 10002 !important;
}


/* 确保图片预览遮罩层在正确层级 */
.el-overlay .picture-preview {
  z-index: 10002 !important;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .left-panel {
    width: 85%;
  }

  .campus-name {
    font-size: 20px;
  }

  .filter-row {
    grid-template-columns: 1fr;
  }
}

.action-btn {
  width: 80px;
  padding: 7px 10px;
}

/* 确保按钮图标和文字间距一致 */
.action-btn :deep(.el-icon) {
  margin-right: 4px;
}

@media (max-width: 768px) {
  .room-management {
    padding: 12px;
    gap: 15px;
  }

  .campus-header {
    flex-direction: column;
    min-height: auto;
  }

  .left-panel {
    width: 100%;
    flex-direction: column;
  }

  .campus-avatar {
    align-self: center;
  }

  .name-area {
    flex-direction: column;
    align-items: flex-start;
  }

  .manage-btn {
    position: static;
    width: 100%;
    margin-top: 15px;
  }

  .stats-grid {
    grid-template-columns: 1fr;
  }

  .filter-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .filter-input,
  .filter-select {
    width: 100%;
    max-width: none;
  }

  .table-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .header-right {
    width: 100%;
    justify-content: space-between;
  }
  .action-buttons {
    flex-direction: column;
    align-items: center;
    gap: 5px;
  }

  .action-btn {
    width: 100%;
    margin: 2px 0;
  }
}


/* 操作栏文字样式 */
.action-text {
  cursor: pointer;
  margin: 0 5px;
}

.action-text.info {
  color: #909399;
}

.action-text.primary {
  color: var(--el-color-primary);
}

.action-text.danger {
  color: var(--el-color-danger);
}

.dialog-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.add-floor-btn {
  margin-bottom: 10px;
}
</style>

<style>
/* 全局样式 - 解决对话框层级问题 */
.building-manage-dialog {
  position: relative;
  z-index: 2000;
}

.delete-confirm-box {
  position: relative;
  z-index: 10000 !important;
}

/* 确保遮罩层正确显示 */
.el-overlay {
  z-index: 1000 !important;
}

.el-overlay:has(.delete-confirm-box) {
  z-index: 9999 !important;
}

</style>